
2
2
.
.
7
7
R
R
e
e
l
l
a
a
t
t
i
i
o
o
n
n
s
s
h
h
i
i
p
p
s
s
Following tutorials show how to create different relationships between Entities/Tables
● @OneToOne
● @OneToMany
● @ManyToMany
Tables relationships are quite a complex topic since relationships ca be implemented in different ways
● inside DB by using Foreign-Key or Join-Table
● inside Code by using unidirectional or bidirectional references
@OneToMany relationship is used when one Entity can be related to only one Entity of another type.
@OneToOne is used when you want to split data into multiple Tables.
For instance instead of having single Table with 20 columns you can have 2 Tables with 10 columns each.
It allows you to logically group data
● first Table can contain Customer's basic information like: FirstName, LastName, Age
● second Table can contain Customer's contact information like: Email, Phone, Address
@OneToOne relationship can be implemented either by using
● Feign Key in which case one Table will have an additional column that points to a related Record in the second Table
● Join Table which holds information which Record are related
@OneToMany relationship is used when single Entity can be related to multiple Entities of another type.
For instance single Author can write multiple Books.
@OneToMany relationship can be implemented either by using
● Feign Key in which case one Table will have an additional column that points to a related Record in the second Table
● Join Table which holds information which Record from first Table is related to which Records from the second Table
@ManyToMany relationship is used when one Entity can be related to multiple Entities of another type and vice versa.
For instance single Author can write multiple Books.
But at the same time Book can be written by multiple Authors.
@OneToMany relationship can be implemented only by using
● Join Table which holds information which Records from first Table are related to which Records from the second Table
Note that by default Hibernate creates two Join Tables and in order to have only one you have to specify owning side.